package com.my.hzb.pro.service;

import java.util.Date;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.my.hzb.entiy.Product;
import com.my.hzb.entiy.ProductExample;
import com.my.hzb.mapper.ProductMapper;

public class ProductServiceImpl implements ProductService {

	private static final Logger log = LogManager.getLogger(ProductServiceImpl.class);
	
	@Autowired
	private ProductMapper productMapper;

	@Override
	public int add(Product product) {
		try{
			product.setCreateTime(new Date());
			product.setUpdateTime(new Date());
			return productMapper.insert(product);
		}catch(Exception e){
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int update(Product product) {
		try{
			product.setUpdateTime(new Date());
			return productMapper.updateByPrimaryKey(product);
		}catch(Exception e){
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int delete(Product product) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Product getOne(Integer id) {
		return productMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<Product> find(Product product) {
		ProductExample example = new ProductExample();
		return productMapper.selectByExample(example);
	}

	@Override
	public int updateStock(Integer id, Integer  type, Integer stock) {
		try{
			Product pro = productMapper.selectByPrimaryKey(id);
			if(null!=pro){
				if(0==type){
					if(pro.getStock()>stock){
						pro.setStock(pro.getStock()-stock);
					}
				}else if(1==type){
					pro.setStock(pro.getStock()+stock);
				}
				pro.setUpdateTime(new Date());
				int num = productMapper.updateByPrimaryKey(pro);
				log.info("修改库存的结果是："+num);
				return num;
			}else{
				log.info("id="+id+",不存在");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public Product getHot() {
		List<Product> list = this.find(new Product());
		if(null!=list){
			return list.get(0);
		}
		return null;
	}

}
